# May 25, 2021

# This files adds equilibrium outcomes to the experimental data
# which is saved as "ExperimentalData.csv"

# The outputs are

# a)  "complete": a formatted/cleaned tibble with the responses by treatment/match/round
# b) "equilibrium.values": a tibble with the continuation value, maximum cost, maximum offer
# etc., which determines the equilibrium offer
# c) "equilibrium.full": the equilibrium dataframe 
#     above along with the RS and RS-VN Treatments (equilibrium.full)
# d) "combined.df.full":  "equilibrium.full" merged with associated experimental outcomes

############################################################
# PRELIMINARY
############################################################
source("loadPackages.R")
loadPackages(c("dplyr", "purrr", "readr", "stringr"))

# The following function helps us calculate continuation values
# and maximum offers, which are necessary for (b)
source("cvFunctions.R")

# The following uses cvFunctions to find cont. values, etc.
# and then merges them with the experimental data
source("eqMerge.R")

# Ensure that working directory is set to the replication folder
# and read in experimental data

complete <- read_csv("ExperimentalData.csv")


# Next we use the eqMerge function to merge the experimental data with equilibrium data

# the eqMerge function merges continuation values for each round/treatment with
# the experimental results, with endogenous treatments subsetted to those comparable
# to the BL and VN treatment that are used as placebos (see Appendix D) and 
# merged with the BL and VN equilibrium predictions accordingly

# (1) equilibrium.full:: equilibrium values for each round
# (2) cv.calculations :: more detailed continuation values, maximum offers, etc.
# (3) combined.df.full:: BL, CP, CP-VN, and VN treatments, along with endogenous
# treatments with selected endowments of 100, merged with equilibrium predictions

eqMerge(treatment.names.full = unique(complete$treatment2), 
        round.vals = c(0:7), experimentalResults = complete) %>%
  set_names("EquilibriumValues.csv",
            "ContValueCalculations.csv",
            "EquilibriumExperimentCombined.csv") %>%
  iwalk(~ write_csv(.x, .y))






